<template>
  <a-layout class="dashboard-container">
    <a-layout-header class="dashboard-header">
      <div class="header-left">
        <a-button @click="toggleSidebar" class="menu-toggle" type="text">
          <MenuFoldOutlined v-if="!isSidebarCollapsed" />
          <MenuUnfoldOutlined v-else />
        </a-button>
        <h1 class="system-title">年轮家族管理系统</h1>
      </div>
      <div class="header-right">
        <a-dropdown>
          <span class="user-info">
            <a-avatar :icon="UserOutlined" size="small" />
            <span class="username">{{ currentUser?.nickname || currentUser?.username || '未知用户' }}</span>
          </span>
          <template #overlay>
            <a-menu @click="handleUserCommand">
              <a-menu-item key="profile">个人资料</a-menu-item>
              <a-menu-item key="settings">系统设置</a-menu-item>
              <a-menu-divider />
              <a-menu-item key="logout">退出登录</a-menu-item>
            </a-menu>
          </template>
        </a-dropdown>
      </div>
    </a-layout-header>
    
    <a-layout>
      <a-layout-sider 
        :width="200" 
        :collapsed="isSidebarCollapsed" 
        :collapsedWidth="80"
        class="dashboard-sider"
        collapsible
        :trigger="null"
      >
        <a-menu
          :selectedKeys="[activeMenu]"
          :openKeys="openKeys"
          mode="inline"
          @select="handleMenuSelect"
          @openChange="onOpenChange"
        >
          <a-menu-item key="/dashboard">
            <HomeOutlined />
            <span>系统首页</span>
          </a-menu-item>
          
          <a-menu-item key="/family-members">
            <UserOutlined />
            <span>成员管理</span>
          </a-menu-item>
          
          <a-menu-item key="/family-tree-visualization">
            <ShareAltOutlined />
            <span>家族树图</span>
          </a-menu-item>
          
          <a-menu-item key="/family-member-map">
            <EnvironmentOutlined />
            <span>地图定位</span>
          </a-menu-item>
          
          <a-menu-item key="/user-permission-management" v-if="isSystemAdmin">
            <LockOutlined />
            <span>权限管理</span>
          </a-menu-item>
          
          <a-menu-item key="/settings">
            <SettingOutlined />
            <span>系统设置</span>
          </a-menu-item>
        </a-menu>
      </a-layout-sider>
      
      <a-layout-content class="dashboard-main">
        <router-view />
      </a-layout-content>
    </a-layout>
  </a-layout>
</template>

<script>
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import api from '../api'
import { 
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  HomeOutlined,
  UserOutlined,
  ShareAltOutlined,
  EnvironmentOutlined,
  LockOutlined,
  SettingOutlined
} from '@ant-design/icons-vue'

export default {
  name: 'Dashboard',
  components: {
    MenuFoldOutlined,
    MenuUnfoldOutlined,
    HomeOutlined,
    UserOutlined,
    ShareAltOutlined,
    EnvironmentOutlined,
    LockOutlined,
    SettingOutlined
  },
  setup() {
    const router = useRouter()
    const route = useRoute()
    const activeMenu = ref('/dashboard')
    const isSidebarCollapsed = ref(false)
    const openKeys = ref([])
    const currentUser = ref(null)
    const isSystemAdmin = ref(false)
    
    // 监听路由变化，更新激活的菜单项
    watch(
      () => route.path,
      (newPath) => {
        activeMenu.value = newPath
      }
    )
    
    // 初始化激活菜单
    onMounted(async () => {
      activeMenu.value = route.path
      await loadUserInfo()
    })
    
    // 加载用户信息
    const loadUserInfo = async () => {
      try {
        const response = await api.get('/auth/info')
        if (response.data.code === 200) {
          currentUser.value = response.data.data
          isSystemAdmin.value = response.data.data.role === 'ADMIN'
        } else {
          message.error('获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        // 如果是401错误，跳转到登录页
        if (error.response && error.response.status === 401) {
          router.push('/login')
        } else {
          message.error('获取用户信息失败')
        }
      }
    }
    
    const toggleSidebar = () => {
      isSidebarCollapsed.value = !isSidebarCollapsed.value
    }
    
    const handleMenuSelect = ({ key }) => {
      router.push(key)
    }
    
    const onOpenChange = (keys) => {
      openKeys.value = keys
    }
    
    const handleUserCommand = ({ key }) => {
      switch (key) {
        case 'profile':
          message.info('个人资料功能待实现')
          break
        case 'settings':
          router.push('/settings')
          break
        case 'logout':
          handleLogout()
          break
      }
    }
    
    const handleLogout = async () => {
      try {
        // 调用后端登出接口
        await api.post('/auth/logout')
      } catch (err) {
        console.error('登出接口调用错误:', err)
      } finally {
        // 执行前端登出清理操作
        // 清除本地存储的token
        localStorage.removeItem('satoken')
        
        // 跳转到登录页
        router.push('/login')
        
        message.success('登出成功')
      }
    }
    
    return {
      activeMenu,
      isSidebarCollapsed,
      openKeys,
      currentUser,
      isSystemAdmin,
      toggleSidebar,
      handleMenuSelect,
      onOpenChange,
      handleUserCommand,
      handleLogout
    }
  }
}
</script>

<style scoped>
.dashboard-container {
  height: 100vh;
}

.dashboard-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
  background-color: #fff;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  color: #000;
}

.header-left {
  display: flex;
  align-items: center;
}

.menu-toggle {
  margin-right: 20px;
  border: none;
}

.system-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #000;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}

.username {
  margin: 0 8px;
  font-size: 14px;
  color: #000;
}

.dashboard-sider {
  background: #fff;
  border-right: 1px solid #e6e6e6;
}

.dashboard-main {
  padding: 20px;
  background-color: #f5f5f5;
  overflow-y: auto;
  margin: 0;
}
</style>